<template>
  <div class="store-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">🏪 门店管理</span>
          <div class="header-actions">
            <el-button type="success" @click="handleImport">
              <el-icon><Upload /></el-icon>
              批量导入
            </el-button>
            <el-button type="warning" @click="handleExport">
              <el-icon><Download /></el-icon>
              导出数据
            </el-button>
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增门店
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="门店名称">
          <el-input v-model="searchForm.name" placeholder="请输入门店名称" clearable />
        </el-form-item>
        <el-form-item label="门店编码">
          <el-input v-model="searchForm.code" placeholder="请输入门店编码" clearable />
        </el-form-item>
        <el-form-item label="所属区域">
          <el-select v-model="searchForm.region" placeholder="请选择区域" clearable>
            <el-option label="华东区" value="east" />
            <el-option label="华南区" value="south" />
            <el-option label="华北区" value="north" />
            <el-option label="西南区" value="southwest" />
            <el-option label="西北区" value="northwest" />
          </el-select>
        </el-form-item>
        <el-form-item label="门店类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
            <el-option label="旗舰店" value="flagship" />
            <el-option label="标准店" value="standard" />
            <el-option label="社区店" value="community" />
            <el-option label="加盟店" value="franchise" />
          </el-select>
        </el-form-item>
        <el-form-item label="营业状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="营业中" value="open" />
            <el-option label="装修中" value="renovation" />
            <el-option label="暂停营业" value="closed" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 统计卡片 -->
      <el-row :gutter="20" class="stat-cards">
        <el-col :xs="12" :sm="6">
          <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
              <el-icon :size="32"><Shop /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">门店总数</div>
              <div class="stat-value">{{ totalStores }}</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="6">
          <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);">
              <el-icon :size="32"><CircleCheck /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">营业中</div>
              <div class="stat-value open">{{ openStores }}</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="6">
          <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
              <el-icon :size="32"><User /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">员工总数</div>
              <div class="stat-value">{{ totalStaff }}</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="6">
          <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
              <el-icon :size="32"><TrendCharts /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">今日销售额</div>
              <div class="stat-value sales">¥{{ todaySales.toLocaleString() }}</div>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 批量操作 -->
      <div v-if="selectedRows.length > 0" class="batch-actions">
        <el-alert :title="`已选择 ${selectedRows.length} 个门店`" type="info" :closable="false">
          <template #default>
            <div class="batch-buttons">
              <el-button size="small" type="primary" @click="handleBatchNotice">批量通知</el-button>
              <el-button size="small" type="warning" @click="handleBatchClose">批量关闭</el-button>
              <el-button size="small" type="danger" @click="handleBatchDelete">批量删除</el-button>
            </div>
          </template>
        </el-alert>
      </div>

      <!-- 门店列表 -->
      <el-table :data="tableData" border stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="code" label="门店编码" width="120" />
        <el-table-column prop="name" label="门店名称" width="180">
          <template #default="{ row }">
            <div class="store-name-cell">
              <el-avatar :size="40" :src="row.logo" />
              <span class="store-name">{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="门店类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTag(row.type)">
              {{ getTypeName(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="region" label="所属区域" width="100">
          <template #default="{ row }">
            {{ getRegionName(row.region) }}
          </template>
        </el-table-column>
        <el-table-column prop="address" label="门店地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="manager" label="店长" width="100" />
        <el-table-column prop="phone" label="联系电话" width="130" />
        <el-table-column prop="staffCount" label="员工数" width="80" align="center" />
        <el-table-column prop="area" label="面积(㎡)" width="100" align="right">
          <template #default="{ row }">
            {{ row.area.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="monthlySales" label="月销售额" width="120" align="right">
          <template #default="{ row }">
            <span class="sales-amount">¥{{ row.monthlySales.toLocaleString() }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="openDate" label="开业日期" width="120" />
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleViewDetail(row)">详情</el-button>
            <el-button link type="success" @click="handleViewDashboard(row)">看板</el-button>
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="warning" @click="handleSettings(row)">设置</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSearch"
        @current-change="handleSearch"
      />
    </el-card>

    <!-- 新增/编辑门店对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="门店名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入门店名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门店编码" prop="code">
              <el-input v-model="formData.code" placeholder="请输入门店编码" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="门店类型" prop="type">
              <el-select v-model="formData.type" placeholder="请选择类型" style="width: 100%">
                <el-option label="旗舰店" value="flagship" />
                <el-option label="标准店" value="standard" />
                <el-option label="社区店" value="community" />
                <el-option label="加盟店" value="franchise" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属区域" prop="region">
              <el-select v-model="formData.region" placeholder="请选择区域" style="width: 100%">
                <el-option label="华东区" value="east" />
                <el-option label="华南区" value="south" />
                <el-option label="华北区" value="north" />
                <el-option label="西南区" value="southwest" />
                <el-option label="西北区" value="northwest" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="门店地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入详细地址" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="店长" prop="manager">
              <el-input v-model="formData.manager" placeholder="请输入店长姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="门店面积" prop="area">
              <el-input-number v-model="formData.area" :min="0" :step="10" style="width: 100%" />
              <span style="margin-left: 5px;">㎡</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开业日期" prop="openDate">
              <el-date-picker
                v-model="formData.openDate"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="营业时间" prop="businessHours">
              <el-input v-model="formData.businessHours" placeholder="如：09:00-21:00" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="营业状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="营业中" value="open" />
                <el-option label="装修中" value="renovation" />
                <el-option label="暂停营业" value="closed" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="门店图片">
          <el-upload
            class="store-uploader"
            action="#"
            :show-file-list="false"
            :on-change="handleLogoChange"
          >
            <img v-if="formData.logo" :src="formData.logo" class="store-logo" />
            <el-icon v-else class="store-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="门店简介">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入门店简介"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, Upload, Download, Shop, CircleCheck, User, TrendCharts
} from '@element-plus/icons-vue'

const router = useRouter()

// 搜索表单
const searchForm = reactive({
  name: '',
  code: '',
  region: '',
  type: '',
  status: ''
})

// 选中的行
const selectedRows = ref([])

// 统计数据
const totalStores = ref(45)
const openStores = ref(38)
const totalStaff = ref(856)
const todaySales = ref(2345678)

// 表格数据
const tableData = ref([
  {
    id: 1,
    code: 'SZ001',
    name: '深圳旗舰店',
    type: 'flagship',
    region: 'south',
    address: '深圳市南山区科技园南区深南大道9988号',
    manager: '张伟',
    phone: '0755-12345678',
    staffCount: 45,
    area: 1200,
    monthlySales: 2456789,
    status: 'open',
    openDate: '2020-01-15',
    logo: 'https://via.placeholder.com/60'
  },
  {
    id: 2,
    code: 'SH001',
    name: '上海陆家嘴店',
    type: 'flagship',
    region: 'east',
    address: '上海市浦东新区陆家嘴环路1000号',
    manager: '李芳',
    phone: '021-87654321',
    staffCount: 38,
    area: 980,
    monthlySales: 1987654,
    status: 'open',
    openDate: '2020-03-20',
    logo: 'https://via.placeholder.com/60'
  },
  {
    id: 3,
    code: 'BJ001',
    name: '北京国贸店',
    type: 'flagship',
    region: 'north',
    address: '北京市朝阳区建国门外大街1号',
    manager: '王强',
    phone: '010-65432109',
    staffCount: 42,
    area: 1100,
    monthlySales: 2234567,
    status: 'open',
    openDate: '2019-11-01',
    logo: 'https://via.placeholder.com/60'
  },
  {
    id: 4,
    code: 'GZ001',
    name: '广州天河店',
    type: 'standard',
    region: 'south',
    address: '广州市天河区天河路228号',
    manager: '陈敏',
    phone: '020-38765432',
    staffCount: 28,
    area: 650,
    monthlySales: 1234567,
    status: 'open',
    openDate: '2021-05-10',
    logo: 'https://via.placeholder.com/60'
  },
  {
    id: 5,
    code: 'CD001',
    name: '成都春熙路店',
    type: 'standard',
    region: 'southwest',
    address: '四川省成都市锦江区春熙路99号',
    manager: '刘洋',
    phone: '028-86543210',
    staffCount: 25,
    area: 580,
    monthlySales: 987654,
    status: 'renovation',
    openDate: '2021-08-15',
    logo: 'https://via.placeholder.com/60'
  }
])

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 5
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = computed(() => formData.id ? '编辑门店' : '新增门店')
const formRef = ref(null)

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  code: '',
  type: '',
  region: '',
  address: '',
  manager: '',
  phone: '',
  area: 0,
  openDate: '',
  businessHours: '',
  status: 'open',
  logo: '',
  description: ''
})

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入门店名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入门店编码', trigger: 'blur' }],
  type: [{ required: true, message: '请选择门店类型', trigger: 'change' }],
  region: [{ required: true, message: '请选择所属区域', trigger: 'change' }],
  address: [{ required: true, message: '请输入门店地址', trigger: 'blur' }],
  manager: [{ required: true, message: '请输入店长姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$|^\d{3,4}-\d{7,8}$/, message: '请输入有效的电话号码', trigger: 'blur' }
  ],
  status: [{ required: true, message: '请选择营业状态', trigger: 'change' }]
}

// 获取类型标签
const getTypeTag = (type) => {
  const map = {
    flagship: '',
    standard: 'success',
    community: 'info',
    franchise: 'warning'
  }
  return map[type] || 'info'
}

// 获取类型名称
const getTypeName = (type) => {
  const map = {
    flagship: '旗舰店',
    standard: '标准店',
    community: '社区店',
    franchise: '加盟店'
  }
  return map[type] || type
}

// 获取区域名称
const getRegionName = (region) => {
  const map = {
    east: '华东区',
    south: '华南区',
    north: '华北区',
    southwest: '西南区',
    northwest: '西北区'
  }
  return map[region] || region
}

// 获取状态标签
const getStatusTag = (status) => {
  const map = {
    open: 'success',
    renovation: 'warning',
    closed: 'danger'
  }
  return map[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const map = {
    open: '营业中',
    renovation: '装修中',
    closed: '暂停营业'
  }
  return map[status] || status
}

// 搜索
const handleSearch = () => {
  console.log('搜索:', searchForm)
  ElMessage.success('查询成功')
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  searchForm.code = ''
  searchForm.region = ''
  searchForm.type = ''
  searchForm.status = ''
  handleSearch()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 新增
const handleAdd = () => {
  Object.assign(formData, {
    id: null,
    name: '',
    code: '',
    type: '',
    region: '',
    address: '',
    manager: '',
    phone: '',
    area: 0,
    openDate: '',
    businessHours: '09:00-21:00',
    status: 'open',
    logo: '',
    description: ''
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  Object.assign(formData, { ...row })
  dialogVisible.value = true
}

// 查看详情
const handleViewDetail = (row) => {
  router.push(`/store/detail/${row.id}`)
}

// 查看看板
const handleViewDashboard = (row) => {
  router.push({
    path: '/store/dashboard',
    query: { storeId: row.id }
  })
}

// 门店设置
const handleSettings = (row) => {
  router.push({
    path: '/store/settings',
    query: { storeId: row.id }
  })
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除门店 "${row.name}" 吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
    handleSearch()
  })
}

// 处理图片上传
const handleLogoChange = (file) => {
  formData.logo = URL.createObjectURL(file.raw)
}

// 对话框关闭
const handleDialogClose = () => {
  formRef.value?.resetFields()
}

// 提交表单
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      console.log('提交表单:', formData)
      ElMessage.success(formData.id ? '更新成功' : '创建成功')
      dialogVisible.value = false
      handleSearch()
    }
  })
}

// 导入
const handleImport = () => {
  ElMessage.info('批量导入功能开发中')
}

// 导出
const handleExport = () => {
  ElMessage.success('正在导出数据')
}

// 批量操作
const handleBatchNotice = () => {
  ElMessage.success(`已向 ${selectedRows.value.length} 个门店发送通知`)
  selectedRows.value = []
}

const handleBatchClose = () => {
  ElMessageBox.confirm(`确定要关闭选中的 ${selectedRows.value.length} 个门店吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('批量关闭成功')
    selectedRows.value = []
  })
}

const handleBatchDelete = () => {
  ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个门店吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('批量删除成功')
    selectedRows.value = []
  })
}
</script>

<style scoped>
.store-list {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
}

/* 统计卡片 */
.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin-right: 15px;
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.stat-value.open {
  color: #67c23a;
}

.stat-value.sales {
  color: #f56c6c;
  font-size: 20px;
}

.batch-actions {
  margin-bottom: 20px;
}

.batch-buttons {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

/* 门店名称单元格 */
.store-name-cell {
  display: flex;
  align-items: center;
  gap: 10px;
}

.store-name {
  font-weight: 500;
}

.sales-amount {
  color: #f56c6c;
  font-weight: bold;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

/* 上传图片 */
.store-uploader {
  display: inline-block;
}

.store-uploader .store-logo {
  width: 120px;
  height: 120px;
  object-fit: cover;
  border-radius: 8px;
}

.store-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.store-uploader-icon:hover {
  border-color: #409eff;
  color: #409eff;
}
</style>

